package pl.prv.polanie.client.dialogs;

import pl.prv.polanie.client.Planner;
import pl.prv.polanie.client.dto.CSGroupDTO;
import pl.prv.polanie.client.dto.CSSubgroupDTO;
import pl.prv.polanie.client.dto.CSSubgroupTypeDTO;
import pl.prv.polanie.client.dto.CSVGroupDTO;
import pl.prv.polanie.client.dto.CSVSubgroupTypeDTO;
import pl.prv.polanie.client.model.Cache;
import pl.prv.polanie.client.model.ServiceHolder;
import pl.prv.polanie.client.model.ViewDataProvider;
import pl.prv.polanie.client.panels.lists.SubgroupsList;
import pl.prv.polanie.client.widgets.CustomDialogBox;
import pl.prv.polanie.client.widgets.SelectBoxWithObjects;
import pl.prv.polanie.client.widgets.TextBoxStyled;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * 
 * @author Janusz Prokulewicz
 * Created: Apr 19, 2008
 */

public class CreateSubgroupDialog extends CustomDialogBox {

	private static final String STYLE__CREATE_SUBJECT_EVENT_DIALOG = "createSubjectEventDialog";
	
	
	/** Podzial, dla ktorego jest tworzony nowy/edytowany istniejacy subjectEvent.*/
	private SubgroupsList subgroupsList = null;
	
	
	
	
	/***/
	private FlexTable widgetsFT = new FlexTable();
	
	private Label subgroupTypeL = new Label("Subgroup type");
	private SelectBoxWithObjects subgroupTypeSB = new SelectBoxWithObjects();
	
//	private Label groupL = new Label("Group");
//	private SelectBoxWithObjects groupSB = new SelectBoxWithObjects();
	
	private Label nameL = new Label("Name");
	private TextBox nameTB = new TextBoxStyled();
	
	private Label studentsNumberL = new Label("Students number");
	private TextBox studentsNumberTB = new TextBoxStyled();


	
	
//	private Button loadDataB = new Button("load dataa");

	private Button saveOrCreateAndCloseB = new Button("save and close");
	private Button saveOrCreateB = new Button("save/create");
	private Button closeB = new Button("close");
	
	
	private Command cmdAfterSaveButtonClicked = null;
	
	
	//referencja do dto edytowanego se
	private CSSubgroupDTO csSubgroupDTO = null;
	
	//id grupy,ktorego podgrupe zajeciowa tworzymy/edytujemy
	private long groupID;
	

	
	public CreateSubgroupDialog(long groupID, SubgroupsList subgroupsList, CSSubgroupDTO csS) {
		this.groupID = groupID;
		this.subgroupsList = subgroupsList;
		this.csSubgroupDTO = csS;
		
		layoutWidgets();
		setupWidgets();

		if (csS != null) {
			setText("Edit subgroup");
		} else {
			setText("Create new subgroup");
		}
		
		setWidget(widgetsFT);
//		setStyleName(STYLE__CREATE_SUBJECT_EVENT_DIALOG);
		
		loadDataToWidgets();
	}



	private void setupWidgets() {
		
		//SUBGROUP TYPE
		subgroupTypeSB.addChangeListener(new ChangeListener() {
			public void onChange(Widget sender) {
				Planner.log("CreateLecturerDialog, subgroupTypeLB, id => " + subgroupTypeSB.getSelectedObject());
			}
		});
		subgroupTypeSB.setWidth("180px");
		subgroupTypeSB.setItemsPanelWidth(200);

		
		
//		//GROUP
//		groupSB.addChangeListener(new ChangeListener() {
//			public void onChange(Widget sender) {
//				Planner.log("CreateLecturerDialog, groupLB, id => " + groupSB.getSelectedObject());
//			}
//		});
//		groupSB.setItemsPanelWidth(200);

		
		nameTB.setText("");
		studentsNumberTB.setText("");
		
		
		
		saveOrCreateB.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				boolean closeWindowAfterSaving = false;
				saveCSSubgroup(closeWindowAfterSaving);
			}
		});
		
		saveOrCreateAndCloseB.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				boolean closeWindowAfterSaving = true;
				saveCSSubgroup(closeWindowAfterSaving);
			}
		});
		
		closeB.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				hide();
			}
		});
		
		
//		loadDataB.addClickListener(new ClickListener() {
//			public void onClick(Widget sender) {
//				loadDataToWidgets();
//			}
//		});
	}



	private void layoutWidgets() {
//		widgetsFT.setWidget(1, 0, groupL);
//		widgetsFT.setWidget(1, 1, groupSB);
		
		widgetsFT.setWidget(0, 0, nameL);
		widgetsFT.setWidget(0, 1, nameTB);
		
		widgetsFT.setWidget(1, 0, subgroupTypeL);
		widgetsFT.setWidget(1, 1, subgroupTypeSB);

		widgetsFT.setWidget(2, 0, studentsNumberL);
		widgetsFT.setWidget(2, 1, studentsNumberTB);

//		widgetsFT.setWidget(3, 0, loadDataB);
		widgetsFT.setWidget(3, 1, saveOrCreateAndCloseB);
		
		widgetsFT.setWidget(4, 0, saveOrCreateB);
		widgetsFT.setWidget(4, 1, closeB);
		
	}
	
	/**
	 * TODO metoda validujaca dane
	 */
	private boolean validateEnteredData() {
		return true;
	}
	

	
	/**
	 * Wczytuje z cache'a dane do kontrolek. W przypadku edycji
	 * istniejacego SE ustawiane sa takze w kontrolkach odpowiednie wartosci.
	 */
	private void loadDataToWidgets() {

		long subgroupTypeID = -1;
//		long groupID = -1;
		String name = "";
		String studentsNumber = "";
		
		if (csSubgroupDTO != null) {
			
			Planner.log("edycja Subgroup");
			
			subgroupTypeID = csSubgroupDTO.getSubgroupTypeID();
//			groupID = csSubgroupDTO.getGroupID();
			name = csSubgroupDTO.getName();
			studentsNumber = "" + csSubgroupDTO.getStudentsNumber();
			
		} else {
			Planner.log("tworzenie subgroup");
		}

		
		
		CSSubgroupTypeDTO[] subgroupTypes = Cache.getAllSubgroupTypes();
		subgroupTypeSB.clear();
		
		for (int i = 0; i < subgroupTypes.length; i++) {
			CSVSubgroupTypeDTO csvST = ViewDataProvider.getCSVSubgroupType(subgroupTypes[i]);
			subgroupTypeSB.addItem(csvST.toLabel(), subgroupTypes[i]);
			
			if (subgroupTypeID == csvST.getId()) {
				subgroupTypeSB.setSelectedIndex(i);
			}
		}
		subgroupTypeSB.sortWithAlphabeticalOrder();

		
//		CSGroupDTO[] groups = Cache.getAllGroups();
//		groupSB.clear();
//		
//		for (int i = 0; i < groups.length; i++) {
//			CSVGroupDTO csvG = ViewDataProvider.getCSVGroup(groups[i]);
//			groupSB.addItem(csvG.toLabelShort(), groups[i]);
//			
//			if (groupID == csvG.getId()) {
//				groupSB.setSelectedIndex(i);
//			}
//		}
		
		
		
		nameTB.setText(name);
		studentsNumberTB.setText("" + studentsNumber);
		
	}

	/**
	 * Zapisuje/aktualizuje subgroup. 
	 * @param closeWindowAfterSaving
	 */
	private void saveCSSubgroup(final boolean closeWindowAfterSaving) {
		if (validateEnteredData()) {
			final CSSubgroupDTO csS = new CSSubgroupDTO();
			
			//w przypadku edycji semester ustawiamy id
			if (csSubgroupDTO != null) {
				csS.setId(csSubgroupDTO.getId());
			}
			
			
			//ustawienie atrybutow w dto
			long subgroupTypeID = ((CSSubgroupTypeDTO)subgroupTypeSB.getSelectedObject()).getId();
			csS.setSubgroupTypeID(subgroupTypeID);
			
//			long groupID = ((CSGroupDTO)groupSB.getSelectedObject()).getId();
			long groupID = this.groupID;
			csS.setGroupID(groupID);
			
			csS.setName(nameTB.getText());
			csS.setStudentsNumber(new Integer(studentsNumberTB.getText()));
			
			
			AsyncCallback callback = new AsyncCallback() {
				public void onFailure(Throwable caught) {
					GWT.log("CreateLecturerDialog.saveCSSubgroup() FAILURE", null);
				}
				public void onSuccess(Object result) {
					Long res = (Long)result;
					GWT.log("CreateLecturerDialog.saveCSSubgroup() SUCCESS -> zwrocone ID = " + res, null);

					
					//update w cache
					csS.setId(res.longValue());
					Cache.saveOrUpdateCSSubgroup(csS);

					
					//TODO dodac do kontrolki tabelki
					if (subgroupsList != null) {
						subgroupsList.addCSSubgroup(csS);
					}


					if (closeWindowAfterSaving) {
						hide();
					}
				}
			};
			
			ServiceHolder.get().saveCSSubgroup(csS, callback);
		}
	}


	public void setCmdAfterSaveButtonClicked(Command cmdAfterSaveButtonClicked) {
		this.cmdAfterSaveButtonClicked = cmdAfterSaveButtonClicked;
	}

}
